package com.wx.nbregisterserver.job;


import com.wx.nbregisterserver.context.CountTimeContext;
import com.wx.nbregisterserver.context.RegisterMapContext;
import com.wx.nbregisterserver.entity.ServerInfomation;
import com.wx.nbregisterserver.heartbeat.HttpHeartBeatStatus;



import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 心跳任务
 */
@Component
@DependsOn({"registerServer","httpHeartBeatStatus","countTimeContext"})
public class HeartBeatJob {


    @Autowired
    private HttpHeartBeatStatus httpHeartBeatStatus;
    @Autowired
    private CountTimeContext countTimeContext;
    public void execute() {
        HashMap<String, ServerInfomation> registerMap = RegisterMapContext.getRegisterMap();
        if (registerMap.size()>0){
            Set<Map.Entry<String, ServerInfomation>> entries = registerMap.entrySet();
            for (Map.Entry<String, ServerInfomation> entry : entries) {
                ServerInfomation value = entry.getValue();
                String ip = value.getIp();
                int port = value.getPort();
                boolean severStatus = httpHeartBeatStatus.getSeverStatus(ip, port);
                System.out.println("severStatus:"+severStatus);
                String serverName = value.getServerName();
                if(severStatus){
                    // 心跳正常
                    System.out.println(serverName+"：工作正常");
                }else {
                    Integer count = countTimeContext.getCount();
                    if(count>4){
                        System.out.println(serverName+"：服务器异常");
                    }else {
                        count++;
                        countTimeContext.setCount(count);
                    }
                }
            }
        }


    }
}
